golang 变量分配是在堆上还是在栈上,函数为什么能返回局部变量

您所在的位置:网站首页 go 堆 栈 golang 变量分配是在堆上还是在栈上,函数为什么能返回局部变量

golang 变量分配是在堆上还是在栈上,函数为什么能返回局部变量

2023-04-14 10:52| 来源: 网络整理| 查看: 265

变量是堆(heap)还是堆栈(stack)

写过c语言都知道,有明确的堆栈和堆的相关概念。而Go声明语法并没有提到堆栈或堆,只是在Go的FAQ里面有这么一段解释:

How do I know whether a variable is allocated on the heap or the stack?

From a correctness standpoint, you don’t need to know. Each variable in Go exists as long as there are references to it. The storage location chosen by the implementation is irrelevant to the semantics of the language.

The storage location does have an effect on writing efficient programs. When possible, the Go compilers will allocate variables that are local to a function in that function’s stack frame. However, if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors. Also, if a local variable is very large, it might make more sense to store it on the heap rather than the stack.

In the current compilers, if a variable has its address taken, that variable is a candidate for allocation on the heap. However, a basic escape analysis recognizes some cases when such variables will not live past the return from the function and can reside on the stack.

意思:从正确的角度来看,您不需要知道。Go中的每个变量都存在,只要有对它的引用即可。实现选择的存储位置与语言的语义无关。

存储位置确实会影响编写高效的程序。如果可能,Go编译器将为该函数的堆栈帧中的函数分配本地变量。但是,如果编译器在函数返回后无法证明变量未被引用,则编译器必须在垃圾收集堆上分配变量以避免悬空指针错误。此外,如果局部变量非常大,将它存储在堆而不是堆栈上可能更有意义。

在当前的编译器中,如果变量具有其地址,则该变量是堆上分配的候选变量。但是,基本的转义分析可以识别某些情况,这些变量不会超过函数的返回值并且可以驻留在堆栈上。

 

函数为什么能返回局部变量 //定义变量返回一个指针int func stackframe1() *int{ var testVarable int = 10 return &testVarable }



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3